# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, request, redirect, flash
from sqlalchemy import desc
from application import app, db
from common.libs.Helper import ops_render, iPagination
from common.libs.Restful import Restful
from common.libs.UrlManager import UrlManager
from common.models.members.Member import Member

route_member = Blueprint('member_page', __name__)


@route_member.route("/index", methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        page = request.args.get('p') if 'p' in request.args else 1
        offset = (page - 1) * app.config['PAGE_SIZE']
        limit = app.config['PAGE_SIZE']*page
        members = Member.query.order_by(Member.id.desc()).all()[offset:limit]
        page_params = {
            'total': len(members),
            'page_size': app.config['PAGE_SIZE'],
            'page': page,
            'display': app.config['PAGE_DISPLAY'],
            'url': request.full_path.replace('?p={}'.format(page), '').replace('?', '')
        }
        pages = iPagination(page_params)
        return ops_render("member/index.html", context={'members': members, 'pages': pages})


@route_member.route("/info")
def info():
    id = request.args.get('id')
    if not id:
        flash(message='没有找到此用户！', category='error')
        return redirect(UrlManager.buildUrl('member/index'))
    member = Member.query.get(id)
    if not member:
        flash(message='没有找到此用户！', category='error')
        return redirect(UrlManager.buildUrl('member/index'))
    return ops_render("member/info.html", context={'member': member})


@route_member.route("/set/", methods=['GET', 'POST'])
def set():
    if request.method == 'GET':
        id = request.args.get('id')
        if not id:
            flash(message='没有找到此用户！', category='error')
            return redirect(UrlManager.buildUrl('member/index'))
        member = Member.query.get(id)
        if not member:
            flash(message='没有找到此用户！', category='error')
            return redirect(UrlManager.buildUrl('member/index'))
        return ops_render("member/set.html", context={'member': member})
    else:
        id = request.form.get('id')
        nickname = request.form.get('nickname')

        if not id:
            return Restful.param_error('缺少参数！')
        if not nickname:
            return Restful.param_error('缺少参数！')

        member = Member.query.get(id)
        if not member:
            return Restful.notfound_error(msg='未找到此用户')
        member.nickname = nickname
        db.session.commit()
        return Restful.success('更新成功！')


@route_member.route("/comment")
def comment():
    return ops_render("member/comment.html")
